from flask import Flask, request, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename
import os

# 设置上传文件的保存路径（放在static目录下）
UPLOAD_FOLDER = os.path.join('static', 'uploads')
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 确保上传目录存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        return upload_file()
    return '''
    <!DOCTYPE html>
    <html>
    <body>
    <form method="post" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit" value="Upload">
    </form>
    </body>
    </html>
    '''

def upload_file():
    if 'file' not in request.files:
        return 'No file part'
    file = request.files['file']
    if file.filename == '':
        return 'No selected file'
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        # 保存文件到static/uploads目录
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        # 返回正确的访问链接
        return f'File uploaded successfully! <a href="/uploads/{filename}">View</a>'
    return 'File type not allowed'

# 新增专门的路由用于访问上传的图片
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

if __name__ == '__main__':
    app.run(debug=True)
